package com.blog.dao;

import com.blog.bean.DbTask;
import com.blog.bean.QueryCallback;

import java.sql.*;

public class JdbcUtil {

    private static final String DB_URL = "jdbc:mysql://47.112.232.11:3306/blog";
    private static final String USER = "blog";
    private static final String PASSWORD = "123456";

    public static void execute(String sql) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        try {
            // 2. 注册驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 3. 获取数据库连接
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            // 4. 执行查询
            statement = connection.createStatement();
            statement.execute(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw e;
        } finally {
            close(statement);
            close(connection);
        }
    }

    public static Object executeQuery(String sql, QueryCallback listener) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            // 2. 注册驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 3. 获取数据库连接
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            // 4. 执行查询
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            if (listener != null) {
                return listener.doResultHandle(resultSet);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw e;
        } finally {
            close(resultSet);
            close(statement);
            close(connection);
        }
        return null;
    }

    public static Object executeDbTask(DbTask task) throws SQLException {
        if (task == null) {
            return null;
        }
        Connection connection = null;
        try {
            // 2. 注册驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 3. 获取数据库连接
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            // 4. 执行查询
            task.setConnection(connection);
            return task.run();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            throw e;
        } finally {
            close(connection);
        }
        return null;
    }

    public static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
